package cn.ug.analyse.web.controller;

import cn.ug.analyse.bean.ChannelMemberBean;
import cn.ug.analyse.bean.request.DormancyMemberParamBean;
import cn.ug.analyse.bean.request.MemberAnalyseParamBean;
import cn.ug.analyse.bean.request.MemberAngParamBean;
import cn.ug.analyse.bean.request.MemberPortrayParamBean;
import cn.ug.analyse.bean.response.*;
import cn.ug.analyse.service.MemberAnalyseService;
import cn.ug.bean.base.DataTable;
import cn.ug.bean.base.Page;
import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.config.Config;
import cn.ug.pay.bean.request.FinanceBillParam;
import cn.ug.pay.bean.response.ActiveMemberBean;
import cn.ug.pay.bean.response.ActiveTotalBean;
import cn.ug.util.ExportExcelUtil;
import cn.ug.util.PaginationUtil;
import cn.ug.util.UF;
import cn.ug.web.controller.ExportExcelController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @auther ywl
 * @date 2018-05-11 15:40:00
 */
@RestController
@RequestMapping("memberAnalyse")
public class MemberAnalyseController {

    @Resource
    private MemberAnalyseService memberAnalyseService;

    @Resource
    private Config config;

    @GetMapping(value = "findList")
    public SerializeObject<DataTable<MemberAnalyseBean>> findList(@RequestHeader String accessToken, MemberAnalyseParamBean entity) {
        if(entity.getPageSize() <= 0) {
            entity.setPageSize(config.getPageSize());
        }
        Page page = new Page();
        page.setPageSize(entity.getPageSize());
        page.setPageNum(entity.getPageNum());
        List<MemberAnalyseBean> list = memberAnalyseService.findList(entity);
        if (list != null && list.size() > 0) {
            page.setTotal(list.size());
            if (page.getPageSize() > 0) {
                list = list.stream().skip((PaginationUtil.getPage(page.getPageNum())-1) * page.getPageSize()).limit(page.getPageSize()).collect(Collectors.toList());
            }
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<MemberAnalyseBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        } else {
            page.setTotal(0);
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<MemberAnalyseBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<MemberAnalyseBean>()));
        }
    }

    @GetMapping(value = "/channel")
    public SerializeObject<MemberAnalyseBean> getChannelDetail(String channelId) {
        channelId = UF.toString(channelId);
        return new SerializeObject(ResultType.NORMAL, memberAnalyseService.getChannelDetail(channelId));
    }

    @GetMapping(value = "/member/list")
    public SerializeObject<DataTable<ChannelMemberBean>> list(Page page, String channelId) {
        channelId = UF.toString(channelId);
        int total = memberAnalyseService.queryForCount(channelId);
        page.setTotal(total);
        if (total > 0) {
            int offset = PaginationUtil.getOffset(page.getPageNum(), page.getPageSize());
            int size = PaginationUtil.getPageSize(page.getPageSize());
            if (page.getPageNum() == 0) {
                offset = 0;
                size = 0;
            }
            List<ChannelMemberBean> list = memberAnalyseService.queryForList(channelId, offset, size);
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<ChannelMemberBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<ChannelMemberBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<ChannelMemberBean>()));
    }

    @GetMapping(value = "/member/export")
    public void exportData(HttpServletResponse response, String channelId) {
        channelId = UF.toString(channelId);
        List<ChannelMemberBean> list = memberAnalyseService.queryForList(channelId, 0, 0);
        if(list != null && list.size() > 0){
            String[] columnNames = { "序号", "名称","注册用户", "注册时间", "认证绑卡时间"};
            String [] columns = {"index",  "name", "mobile", "registerTime", "bindedCardTime"};
            int index = 1;
            for (ChannelMemberBean bean : list) {
                bean.setIndex(index);
                index++;
                if (StringUtils.isBlank(bean.getName())) {
                    bean.setName("");
                }
                if (StringUtils.isBlank(bean.getBindedCardTime())) {
                    bean.setBindedCardTime("");
                }
            }
            String fileName = "渠道注册用户列表";
            ExportExcelController<ChannelMemberBean> export = new ExportExcelController<ChannelMemberBean>();
            export.exportExcel(fileName, fileName, columnNames, columns, list, response, ExportExcelUtil.EXCEL_FILE_2003);
        }
    }

    @GetMapping(value = "/new/user")
    public SerializeObject<List<MemberAnalyseBean>> listNewUser(String startTime, String endTime, String[] channelIds) {
        MemberAnalyseParamBean financeBillParam = new MemberAnalyseParamBean();
        financeBillParam.setChannelIds(channelIds);
        financeBillParam.setPageNum(1);
        financeBillParam.setPageSize(1000000);
        financeBillParam.setStartTime(startTime);
        financeBillParam.setEndTime(endTime);
        List<MemberAnalyseBean> list = memberAnalyseService.findList(financeBillParam);
        return new SerializeObject(ResultType.NORMAL, list);
    }

    /**
     * 会员分析累计
     * @param accessToken
     * @return
     */
    @GetMapping(value = "findMemberAnalyseTotal")
    public SerializeObject<MemberAnalyseTotalBean> findMemberAnalyseTotal(@RequestHeader String accessToken, MemberAnalyseParamBean memberAnalyseParamBean) {
        List<MemberAnalyseBean> list = memberAnalyseService.findList(memberAnalyseParamBean);
        MemberAnalyseTotalBean entity = new MemberAnalyseTotalBean();
        if (list != null && list.size() > 0) {
            for (MemberAnalyseBean bean : list) {
                entity.setBindingBankCardNumber(entity.getBindingBankCardNumber()+bean.getBindingBankCardNumber());
                entity.setRechargeNumber(entity.getRechargeNumber()+bean.getRechargeNumber());
                entity.setRegisterNumber(entity.getRegisterNumber()+bean.getRegisterNumber());
                entity.setTradeNumber(entity.getTradeNumber()+bean.getTradeNumber());
            }
        }
        return new SerializeObject(ResultType.NORMAL, entity);
    }

    /**
     * 会员转化率
     * @param accessToken
     * @return
     */
    @GetMapping(value = "findMemberAnalysePer")
    public SerializeObject<MemberAnalysePerBean> findMemberAnalysePer(@RequestHeader String accessToken,String channelId) {
        MemberAnalyseParamBean financeBillParam = new MemberAnalyseParamBean();
        String[] channelIds = {channelId};
        financeBillParam.setChannelIds(channelIds);
        financeBillParam.setPageNum(1);
        financeBillParam.setPageSize(10);
        financeBillParam.setStartTime("");
        financeBillParam.setEndTime("");
        List<MemberAnalyseBean> list = memberAnalyseService.findList(financeBillParam);
        MemberAnalysePerBean perBean = new MemberAnalysePerBean();
        if (list != null && list.size() > 0) {
            MemberAnalyseBean totalBean = list.get(0);
            DecimalFormat df = new DecimalFormat("0.0000");
            if(totalBean.getRegisterNumber() ==0 || totalBean.getBindingBankCardNumber()==0){
                perBean.setBindingBankCardPer(BigDecimal.ZERO.toString());
            }else{
                perBean.setBindingBankCardPer(df.format(totalBean.getBindingBankCardNumber()*1.0/totalBean.getRegisterNumber()));
            }
            if(totalBean.getRechargeNumber() == 0 || totalBean.getRegisterNumber() ==0){
                perBean.setRechargePer(BigDecimal.ZERO.toString());
            }else{
                perBean.setRechargePer(df.format(totalBean.getRechargeNumber()*1.0/totalBean.getRegisterNumber()));
            }
            if(totalBean.getTradeNumber() ==0 || totalBean.getRegisterNumber() == 0){
                perBean.setTradePer(BigDecimal.ZERO.toString());
            }else{
                perBean.setTradePer(df.format(totalBean.getTradeNumber()*1.0/totalBean.getRegisterNumber()));
            }
        }
        return new SerializeObject(ResultType.NORMAL, perBean);
    }

    /**
     * 会员活跃用户统计
     * @param accessToken
     * @return
     */
    @GetMapping(value = "findBuySellActiveMemberList")
    public SerializeObject<DataTable<ActiveMemberBean>> findBuySellActiveMemberList(@RequestHeader String accessToken, FinanceBillParam financeBillParam) {
        DataTable<ActiveMemberBean> list = memberAnalyseService.findBuySellActiveMemberList(financeBillParam);
        return new SerializeObject(ResultType.NORMAL, list);
    }

    @GetMapping(value = "/active/user")
    public SerializeObject<List<ActiveMemberAnalyseBean>> listActiveUser(int dayType, String startTime, String endTime, String[] channelIds) {
        FinanceBillParam financeBillParam = new FinanceBillParam();
        financeBillParam.setChannelIds(channelIds);
        financeBillParam.setPageNum(1);
        financeBillParam.setPageSize(1000000);
        financeBillParam.setDayType(dayType);
        financeBillParam.setStartTime(startTime);
        financeBillParam.setEndTime(endTime);
        DataTable<ActiveMemberBean> list = memberAnalyseService.findBuySellActiveMemberList(financeBillParam);
        List<ActiveMemberAnalyseBean> result = new ArrayList<ActiveMemberAnalyseBean>();
        if (list != null && list.getDataList() != null) {
            List<ActiveMemberBean> beans = list.getDataList();
            for (ActiveMemberBean bean : beans) {
                ActiveMemberAnalyseBean analyseBean = new ActiveMemberAnalyseBean();
                analyseBean.setDay(bean.getDay());
                analyseBean.setBuyNumber(bean.getBuyNumber() == null ? 0 : bean.getBuyNumber());
                analyseBean.setNumber(bean.getNumber() == null ? 0 : bean.getNumber());
                analyseBean.setSellerNumber(bean.getSellerNumber() == null ? 0 : bean.getSellerNumber());
                result.add(analyseBean);
            }

        }
        return new SerializeObject(ResultType.NORMAL, result);
    }

    /**
     * 会员活跃用户数量
     * @param accessToken
     * @return
     */
    @GetMapping(value = "findBuySellActiveMemberTotal")
    public SerializeObject<DataTable<ActiveTotalBean>> findBuySellActiveMemberTotal(@RequestHeader String accessToken, FinanceBillParam financeBillParam) {
        List<ActiveTotalBean> list = memberAnalyseService.findBuySellActiveMemberTotal(financeBillParam);
        return new SerializeObject(ResultType.NORMAL, list);
    }

    /**
     * 休眠会员统计
     * @param accessToken
     * @return
     */
    @GetMapping(value = "findDormancyMember")
    public SerializeObject findDormancyMember(@RequestHeader String accessToken, DormancyMemberParamBean paramBean) {
        Map<String,Object> map = memberAnalyseService.findDormancyMember(paramBean);
        return new SerializeObject(ResultType.NORMAL, map);
    }

    /**
     * 统计
     * @param accessToken
     * @return
     */
    @GetMapping(value = "findMemberProtrayList")
    public SerializeObject<List<MemberProtrayBean>> findMemberProtrayList(@RequestHeader String accessToken, MemberPortrayParamBean paramBean) {
        List<MemberProtrayBean> list = memberAnalyseService.findMemberProtrayList(paramBean);
        return new SerializeObject(ResultType.NORMAL, list);
    }

    /**
     * 根据年龄获取数据
     * @param accessToken
     * @return
     */
    @GetMapping(value = "findAgeProtrayList")
    public SerializeObject<List<MemberProtrayBean>> findAgeProtrayList(@RequestHeader String accessToken) {
        List<MemberProtrayBean> list = memberAnalyseService.findAgeProtrayList();
        return new SerializeObject(ResultType.NORMAL, list);
    }

    /**
     * 统计年龄分布
     * @param accessToken
     * @param memberAngParamBean
     * @return
     */
    @GetMapping(value = "findMemberAgeList")
    public SerializeObject<List<String>> findMemberProtrayList(@RequestHeader String accessToken,MemberAngParamBean memberAngParamBean) {
        List<MemberRatioBean> list = memberAnalyseService.findMemberAgeList(memberAngParamBean);
        return new SerializeObject(ResultType.NORMAL, list);
    }

    /**
     * 统计终端用户
     * @param accessToken
     * @return
     */
    @GetMapping(value = "findTerminalMember")
    public SerializeObject<List<Integer>> findTerminalMember(@RequestHeader String accessToken) {
        List<Integer> list = memberAnalyseService.findTerminalMember();
        return new SerializeObject(ResultType.NORMAL, list);
    }

   /* *//**
     * 统计会员总数
     * @param accessToken
     * @return
     *//*
    @GetMapping(value = "findRegisterMember")
    public SerializeObject findRegisterMember(@RequestHeader String accessToken) {
        return new SerializeObject(ResultType.NORMAL, memberAnalyseService.findRegisterMember());
    }*/

    /**
     * 邀请比例
     * @param accessToken
     * @return
     */
    @GetMapping(value = "findMemberFriendList")
    public SerializeObject<List<String>> findMemberFriendList(@RequestHeader String accessToken,MemberAngParamBean memberAngParamBean) {
        List<MemberRatioBean> list = memberAnalyseService.findMemberFriendList(memberAngParamBean);
        return new SerializeObject(ResultType.NORMAL, list);
    }

    /**
     * 查询用户交易时间段
     * @param accessToken
     * @param memberAngParamBean
     * @return
     */
    @GetMapping(value = "findMemberIdNumTodayTrader")
    public SerializeObject<MemberTraderRonseespBean> findMemberIdNumTodayTraderList(@RequestHeader String accessToken,MemberAngParamBean memberAngParamBean) {
        MemberTraderRonseespBean memberTraderRonseespBean = memberAnalyseService.findMemberIdNumTodayTraderList(memberAngParamBean);
        return new SerializeObject(ResultType.NORMAL, memberTraderRonseespBean);
    }

}
